package com.example.cafe.work.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.example.cafe.work.dto.Result;
import com.example.cafe.work.dto.UserDTO;
import com.example.cafe.work.dto.UserSenstive;
import com.example.cafe.work.model.User;
import com.example.cafe.work.mapper.UserMapper;
import com.example.cafe.work.model.Userinfo;
import com.example.cafe.work.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.cafe.work.util.Uuid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import static com.example.cafe.work.util.RedisConstants.LOGIN_USER_KEY;
import static com.example.cafe.work.util.RedisConstants.LOGIN_USER_TTL;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hua
 * @since 2024-09-16
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    @Transactional
    public Result addUser(User user) {
        //添加用户，传过来的是username和password
        user.setUserId(Uuid.getid());
        //先对user表添加数据，加事务和异常判断
        boolean save = save(user);
        if(!save){
            throw new RuntimeException("添加用户失败");
        }
        //添加对应的userinfo表的数据，传id，其他数据库都有默认值
        Userinfo userinfo = new Userinfo();
        userinfo.setUserId(user.getUserId());
        //在UserMapper中自定义sql语句
        int i = userMapper.addUserInfo(userinfo);
        System.out.println(i);
        if(i==0){
            throw new RuntimeException("添加用户信息失败2");
        }
        return Result.ok();
    }

    @Override
    public Result select(String name, int page, int size) {
        //分页加模糊查询
        int start = page*size - size;

        List<UserDTO> userDTOS = userMapper.selectPage1(start, size, name);
        return Result.ok(userDTOS);
    }

    @Override
    public Result login(String userName, String password) {
        User user = query().eq("user_name", userName).eq("user_pwd", password).one();
        if (user==null){
            throw new RuntimeException("用户不存在");
        }
        //生成token值，也就是传到前端的authorization,由于已经加了拦截，后面的所有请求都要带token
        String token = Uuid.getToken();
        //数据脱敏，只返回一个经过hash计算后的对象到前端，只暴露一个id，id也需要加密，防止通过id推算系统的架构等
        UserSenstive userSenstive = BeanUtil.copyProperties(user,UserSenstive.class);
        HashMap<Object, Object> userMap = new HashMap<>();
        userMap.put("userId",userSenstive.getUserId());
        userMap.put("nickName",userSenstive.getNickName());
        userMap.put("icon",userSenstive.getIcon());
        //设置redis中的键
        String key = LOGIN_USER_KEY+token;
        HashOperations<String, Object, Object> hashRedis = stringRedisTemplate.opsForHash();
        //存入redis中
        hashRedis.putAll(key,userMap);
        //设置过期时间
        stringRedisTemplate.expire(key,LOGIN_USER_TTL, TimeUnit.MINUTES);
        //返回token，后续拿token传请求
        return Result.ok(token);

    }
}
